<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        const PENDING = 'PENDING'; // 进行中
        const FULFILLED = 'FULFILLED'; // 已成功
        const REJECTED = 'REJECTED'; // 已失败

        class Promise_ {
            constructor(executor) {
                // 初始化状态
                this.status = PENDING;
                // 将成功、失败结果放在this上，便于then、catch访问
                this.value = undefined;
                this.reason = undefined;
                // 成功态回调函数队列
                this.onFulfilledCallbacks = [];
                // 失败态回调函数队列
                this.onRejectedCallbacks = [];

                const resolve = value => {
                    // 只有进行中状态才能更改状态
                    if (this.status === PENDING) {
                        this.status = FULFILLED;
                        this.value = value;
                        // 成功态函数依次执行
                        this.onFulfilledCallbacks.forEach(fn => fn(this.value));
                    }
                }
                const reject = reason => {
                    // 只有进行中状态才能更改状态
                    if (this.status === PENDING) {
                        this.status = REJECTED;
                        this.reason = reason;
                        // 失败态函数依次执行
                        this.onRejectedCallbacks.forEach(fn => fn(this.reason))
                    }
                }
                try {
                    // 立即执行executor
                    // 把内部的resolve和reject传入executor，用户可调用resolve和reject
                    executor(resolve, reject);
                } catch (e) {
                    // executor执行出错，将错误内容reject抛出去
                    reject(e);
                }
            }
            then(onFulfilled, onRejected) {
                onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : (value) =>{return value;};
                onRejected = typeof onRejected === 'function' ? onRejected :
                    (reason) => {
                        throw new Error(reason instanceof Error ? reason.message : reason)
                    }
                // 保存this
                const self = this;
                //then函数要返回一个promise
                return new Promise_((resolve, reject) => {
                    console.log('then return::',self.status)
                    if (self.status === PENDING) {
                        self.onFulfilledCallbacks.push(() => {
                            // try捕获错误
                            try {
                                // 模拟微任务
                                setTimeout(() => {
                                    const result = onFulfilled(self.value);
                                    // 分两种情况：
                                    // 1. 回调函数返回值是Promise，执行then操作
                                    // 2. 如果不是Promise，调用新Promise的resolve函数
                                    result instanceof Promise_ ? result.then(resolve, reject) : resolve(result);
                                })
                            } catch (e) {
                                reject(e);
                            }
                        });
                        self.onRejectedCallbacks.push(() => {
                            // 以下同理
                            try {
                                setTimeout(() => {
                                    const result = onRejected(self.reason);
                                    // 不同点：此时是reject
                                    result instanceof Promise_ ? result.then(resolve, reject) : reject(result);
                                })
                            } catch (e) {
                                reject(e);
                            }
                        })
                    } else if (self.status === FULFILLED) {
                        try {
                            setTimeout(() => {
                                const result = onFulfilled(self.value);
                                result instanceof Promise_ ? result.then(resolve, reject) : resolve( result);
                            });
                        } catch (e) {
                            reject(e);
                        }
                    } else if (self.status === REJECTED) {
                        try {
                            setTimeout(() => {
                                const result = onRejected(self.reason);
                                result instanceof Promise_ ? result.then(resolve, reject) : reject( result);
                            })
                        } catch (e) {
                            reject(e);
                        }
                    }
                });
            }
            catch(onRejected) {
                return this.then(null, onRejected);
            }
            static resolve(value) {//类的静态方法，直接通过类名调用
                if (value instanceof Promise_) {
                    // 如果是Promise实例，直接返回
                    return value;
                } else {
                    // 如果不是Promise实例，返回一个新的Promise对象，状态为FULFILLED
                    return new Promise_((resolve, reject) => resolve(value));
                }
            }
            static reject(reason) {//类的静态方法，直接通过类名调用
                return new Promise_((resolve, reject) => {
                    reject(reason);
                })
            }
        }
        new Promise_((resolve)=>{
            resolve(123321)
        }).then(res=>{
            console.log('then::',res)
            return 666
        })
        // .then(res=>{
        //     console.log(res)
        //     return 777
        // }).then(res=>{
        //     console.log(res)
        // })
    </script>
</body>

</html>